package com.kedacom.freedomLabel.view.activity;

import android.app.AlertDialog;
import android.arch.lifecycle.Observer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseActivity;
import com.kedacom.freedomLabel.databinding.ActivityBusinessBinding;
import com.kedacom.freedomLabel.databinding.ItemBusiSelectitemBinding;
import com.kedacom.freedomLabel.databinding.ItemDatahistoryBinding;
import com.kedacom.freedomLabel.model.annotation.ItemCategory;
import com.kedacom.freedomLabel.model.bean.Business;
import com.kedacom.freedomLabel.model.bean.Category;
import com.kedacom.freedomLabel.model.bean.Item;
import com.kedacom.freedomLabel.model.bean.ItemCategoryName;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.DataCallback;
import com.kedacom.freedomLabel.model.db.DataLoader;
import com.kedacom.freedomLabel.model.db.dao.BusinessDao;
import com.kedacom.freedomLabel.utils.DistenUtils;
import com.kedacom.freedomLabel.utils.IPUtil;
import com.kedacom.freedomLabel.utils.NumFormatUtil;
import com.kedacom.freedomLabel.viewmodel.BusinessViewModel;
import com.kedacom.lego.adapter.recyclerview.LegoBaseRecyclerViewAdapter;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.OnMessage;
import com.kedacom.lego.annotation.ViewModel;
import com.kedacom.lego.message.LegoMessageManager;
import com.seray.scaleviewlib.utils.LogUtils;
import com.tscale.scalelib.jniscale.JNIScale;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * 称重界面记录数据界面==》生成business
 */
@ContentView(R.layout.activity_business)
@ViewModel(BusinessViewModel.class)
public class BusinessActivity extends BaseActivity<ActivityBusinessBinding, BusinessViewModel> {

    private LegoBaseRecyclerViewAdapter itemAdapter;
    private LegoBaseRecyclerViewAdapter dataHistoryAdapter;
    private int curpos;
    private Boolean isTest = Boolean.FALSE;
    private JNIScale mScale;
    private ScaleHandler mScaleHandler = new ScaleHandler(new WeakReference<>(this));
    private ScheduledExecutorService timerThreads = Executors.newScheduledThreadPool(1);
    private String curGrossWeight;

    private BroadcastReceiver timeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            assert action != null;
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                mBinding.time.setText(NumFormatUtil.getFormatDate());
            }
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTest) {
            register();
            initJNI();
            timer();
            String localIpStr = IPUtil.getLocalIpStr(getApplicationContext());
            mBinding.maxUnit.setText(localIpStr);
        }


        mViewModel.getCount();
        mViewModel.busicount.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer integer) {
                mBinding.total.setText(String.valueOf(integer));
            }
        });

        mViewModel.mItems.observe(this, new Observer<List<Item>>() {
            @Override
            public void onChanged(@Nullable List<Item> items) {
                //显示一个弹框
                showSingleDialog(items);
            }
        });

        mBinding.itemRecycler.setLayoutManager(new LinearLayoutManager(this));
        itemAdapter = new LegoBaseRecyclerViewAdapter(R.layout.item_busi_selectitem, new ArrayList(), com.kedacom.freedomLabel.BR.selectItem) {
            @Override
            protected void onCustomBindItem(ViewDataBinding binding, int position) {
                super.onCustomBindItem(binding, position);
                ItemBusiSelectitemBinding binding1 = (ItemBusiSelectitemBinding) binding;
                switch (position) {
                    case 0:
                        binding1.itemnum.setText(ItemCategory.ITEM_1);
                        break;
                    case 1:
                        binding1.itemnum.setText(ItemCategory.ITEM_2);
                        break;
                    case 2:
                        binding1.itemnum.setText(ItemCategory.ITEM_3);
                        break;
                    case 3:
                        binding1.itemnum.setText(ItemCategory.ITEM_4);
                        break;
                    case 4:
                        binding1.itemnum.setText(ItemCategory.ITEM_5);
                        break;
                    case 5:
                        binding1.itemnum.setText(ItemCategory.ITEM_6);
                        break;
                    default:
                        break;
                }
                ((ItemBusiSelectitemBinding) binding).itemDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        beep();
                        if (!TextUtils.isEmpty(((ItemBusiSelectitemBinding) binding).itemselectvalue.getText().toString())) {
                            ItemCategoryName data = (ItemCategoryName) itemAdapter.getData().get(position);
                            ((ItemBusiSelectitemBinding) binding).itemselectvalue.setText("点击选择");
                            data.setItem(null);
                            notifyDataSetChanged();
                        }
                    }
                });
                ((ItemBusiSelectitemBinding) binding).itemselectvalue.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        beep();
                        curpos = position;

//                        Intent intent = new Intent(BusinessActivity.this, ItemSelectActivity.class);
                        String type = ItemCategory.ITEM_1;
                        switch (position) {
                            case 0:
                                type = ItemCategory.ITEM_1;
                                break;
                            case 1:
                                type = ItemCategory.ITEM_2;
                                break;
                            case 2:
                                type = ItemCategory.ITEM_3;
                                break;
                            case 3:
                                type = ItemCategory.ITEM_4;
                                break;
                            case 4:
                                type = ItemCategory.ITEM_5;
                                break;
                            case 5:
                                type = ItemCategory.ITEM_6;
                                break;
                        }

                        mViewModel.getCurCategoryItems(mViewModel.category.getValue().uuid, type);
//                        intent.putExtra(Options.KEY_ITEM_CATEGORY, type);
//                        intent.putExtra(Options.SELECT_ITEM_FROM, "business");
//                        startActivity(intent);
                    }
                });

            }
        };
        mBinding.itemRecycler.setAdapter(itemAdapter);
        mBinding.dataRecy.setLayoutManager(new LinearLayoutManager(this));
        dataHistoryAdapter = new LegoBaseRecyclerViewAdapter(R.layout.item_datahistory, new ArrayList(), com.kedacom.freedomLabel.BR.dataHistory) {
            @Override
            protected void onCustomBindItem(ViewDataBinding binding, int position) {
                super.onCustomBindItem(binding, position);
                ItemDatahistoryBinding binding1 = (ItemDatahistoryBinding) binding;
            }
        };
        mBinding.dataRecy.setAdapter(dataHistoryAdapter);
        mViewModel.category.observe(this, new Observer<Category>() {
            @Override
            public void onChanged(@Nullable Category category) {
//                mBinding.upper.setText(category.upper);
//                mBinding.low.setText(category.low);
            }
        });
        mViewModel.mItemCategoryName.observe(this, new Observer<List<ItemCategoryName>>() {
            @Override
            public void onChanged(@Nullable List<ItemCategoryName> itemCategoryNames) {
                itemAdapter.setData(itemCategoryNames);
            }
        });
    }


    private void showSingleDialog(List<Item> data) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择属性：");

        final String items[] = new String[data.size()];
        for (int i = 0; i < data.size(); i++) {
            items[i] = data.get(i).value;
        }
        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                beep();
                String item = items[which];
                LegoMessageManager.getInstance().sendMessage(Options.MSG_BUSI_SELECT_ITEM, data.get(which));
                dialog.dismiss();

            }
        });

        builder.show();
    }

    private void register() {
        IntentFilter timeFilter = new IntentFilter();
        timeFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(timeReceiver, timeFilter);
    }


    //保存数据
    public void onBtnSaveClick(View view) {
        beep();
        Business business = new Business();
        business.category = mViewModel.category.getValue().name;
        if (isTest) {
            Random random = new Random();
            DecimalFormat df = new DecimalFormat("0.00");
            double aa = (random.nextDouble()) * (random.nextInt(Integer.MAX_VALUE));
            System.out.println(df.format(aa));
            business.grossWeight = String.valueOf(df.format(aa));
            business.netWeight = String.valueOf(df.format(aa));
        } else {
            business.netWeight = mBinding.weight.getText().toString();
            business.grossWeight = curGrossWeight;
        }
//        business.low = mViewModel.category.getValue().low;
//        business.upper = mViewModel.category.getValue().upper;

        BusinessDao businessDao = AppDatabase.getInstance().businessDao();
        DataLoader.save(businessDao, business, new DataCallback<Business>() {
            @Override
            public void success(@Nullable Business data) {
                showToast("数据保存成功", TOAST_SUCCESS);
                //更新数据
                dataHistoryAdapter.addItem(data);
                dataHistoryAdapter.notifyDataSetChanged();
                mViewModel.busicount.setValue(mViewModel.busicount.getValue() + 1);
            }

            @Override
            public void error(@Nullable String errorMessage) {
                showToast("数据保存失败", TOAST_ERROR);
            }
        });
    }

    public void onBtnPrintClick(View view) {
        beep();
    }

    public void onBtnMenuClick(View view) {
        beep();
        startActivity(new Intent(BusinessActivity.this, MainActivity.class));
        finish();
    }

    public void onBtnZeroClick(View view) {
        beep();
        scalesToZero();
    }

    public void onBtnPeelClick(View view) {
        beep();
        scalesToTare();
    }

    @OnMessage(value = Options.MSG_BUSI_SELECT_ITEM)
    public void getItem(Item item) {
        mViewModel.mItemCategoryName.getValue().get(curpos).setItem(item);
        itemAdapter.setData(mViewModel.mItemCategoryName.getValue());
    }


    private void initJNI() {
        mScale = JNIScale.getScale();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!isTest) {
            mScaleHandler.removeCallbacksAndMessages(null);
            timerThreads.shutdownNow();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!isTest) {
            mScaleHandler.sendEmptyMessage(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isTest) {
            mScaleHandler.sendEmptyMessage(1);
        }
    }


    /**
     * 用于数据生成前判断、稳定标识的展示与隐藏
     *
     * @return 是否稳定
     */
    private boolean isStable() {
        return mScale.getStabFlag();
    }

    /**
     * 用于零点标识的展示与隐藏
     *
     * @return 是否在零点
     */
    private boolean isZero() {
        return mScale.getZeroFlag();
    }

    /**
     * 用于数据生成前判断
     *
     * @return 是否超量程
     */
    private boolean isOL() {
        return mScale.getStringNet().contains("OL");
    }

    private int getWeightColor(String weight) {
        // todo 需要处理没有选择categories，上下限为''的情况
        if (DistenUtils.isMoreThanMost(new BigDecimal(weight), new BigDecimal(mBinding.upper.getText().toString()))) {//大于最大
            return R.color.text_orange;
        } else if (DistenUtils.isLowerThanMin(new BigDecimal(weight), new BigDecimal(mBinding.low.getText().toString()))) {//小于最小
            return R.color.text_red;
        } else {
            return R.color.text_green;
        }
    }

    private static class ScaleHandler extends Handler {
        WeakReference<BusinessActivity> mWeakReference;

        ScaleHandler(WeakReference<BusinessActivity> weakReference) {
            this.mWeakReference = weakReference;
        }

        @Override
        public void handleMessage(Message msg) {
            BusinessActivity activity = mWeakReference.get();
            if (activity == null) {
                return;
            }
            if (msg.what == 1) {
                activity.NewWeightChanged();
            }
        }
    }

    /**
     * 加载重物保存
     */
    private void NewWeightChanged() {
        if (isStable()) {
            mBinding.stable.setVisibility(View.VISIBLE);
        } else {
            mBinding.stable.setVisibility(View.INVISIBLE);
        }

        if (isZero()) {
            mBinding.zero.setVisibility(View.VISIBLE);
        } else {
            mBinding.zero.setVisibility(View.INVISIBLE);
        }


        if (isZero()) {
            mBinding.weight.setText("0");
            mBinding.weight.setTextColor(getResources().getColor(R.color.text_red));
            curGrossWeight = "0";
        } else if (isOL()) {
            mBinding.weight.setText("--OL--");
            mBinding.weight.setTextColor(getResources().getColor(R.color.text_orange));
            curGrossWeight = "---0L---";
        } else {
            float currWeightFloat = mScale.getFloatNet();
            mBinding.weight.setText(mScale.getStringNet());
            mBinding.weight.setTextColor(getResources().getColor(getWeightColor(String.valueOf(currWeightFloat))));
            curGrossWeight = mScale.getStringGross();
        }
    }

    // 定时器
    private void timer() {
        Runnable timerRun = () -> {
            try {
                mScaleHandler.sendEmptyMessage(1);
            } catch (Exception ex) {
                LogUtils.e(ex.getMessage());
            }
        };
        timerThreads.scheduleAtFixedRate(timerRun, 1500, 100, TimeUnit.MILLISECONDS);
    }


    // 清零
    private void scalesToZero() {
        mScale.zero();
    }

    // 去皮
    private void scalesToTare() {
        mScale.tare();
    }

}
